import { ref, watch, onMounted } from 'vue'

export type Theme = 'light' | 'dark' | 'auto'

const THEME_KEY = 'app-theme'

// 当前主题
const currentTheme = ref<Theme>('light')

// 实际应用的主题（考虑auto模式）
const appliedTheme = ref<'light' | 'dark'>('light')

/**
 * 获取系统主题偏好
 */
function getSystemTheme(): 'light' | 'dark' {
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    return 'dark'
  }
  return 'light'
}

/**
 * 应用主题到DOM
 */
function applyTheme(theme: 'light' | 'dark') {
  const root = document.documentElement

  if (theme === 'dark') {
    root.classList.add('dark-theme')
    root.classList.remove('light-theme')
  } else {
    root.classList.add('light-theme')
    root.classList.remove('dark-theme')
  }

  appliedTheme.value = theme
}

/**
 * 更新实际应用的主题
 */
function updateAppliedTheme() {
  if (currentTheme.value === 'auto') {
    applyTheme(getSystemTheme())
  } else {
    applyTheme(currentTheme.value)
  }
}

/**
 * 主题管理 Composable
 */
export function useTheme() {
  /**
   * 初始化主题
   */
  const initTheme = () => {
    // 从本地存储读取主题偏好
    const savedTheme = localStorage.getItem(THEME_KEY) as Theme
    if (savedTheme && ['light', 'dark', 'auto'].includes(savedTheme)) {
      currentTheme.value = savedTheme
    } else {
      // 默认跟随系统
      currentTheme.value = 'auto'
    }

    updateAppliedTheme()

    // 监听系统主题变化
    if (window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      mediaQuery.addEventListener('change', (e) => {
        if (currentTheme.value === 'auto') {
          applyTheme(e.matches ? 'dark' : 'light')
        }
      })
    }
  }

  /**
   * 设置主题
   */
  const setTheme = (theme: Theme) => {
    currentTheme.value = theme
    localStorage.setItem(THEME_KEY, theme)
    updateAppliedTheme()
  }

  /**
   * 切换主题（在light和dark之间切换）
   */
  const toggleTheme = () => {
    if (currentTheme.value === 'auto') {
      // 如果是auto，切换到相反的主题
      const systemTheme = getSystemTheme()
      setTheme(systemTheme === 'dark' ? 'light' : 'dark')
    } else {
      // 在light和dark之间切换
      setTheme(currentTheme.value === 'dark' ? 'light' : 'dark')
    }
  }

  /**
   * 获取当前主题
   */
  const getTheme = () => currentTheme.value

  /**
   * 获取实际应用的主题
   */
  const getAppliedTheme = () => appliedTheme.value

  /**
   * 检查是否为深色模式
   */
  const isDark = () => appliedTheme.value === 'dark'

  return {
    currentTheme,
    appliedTheme,
    initTheme,
    setTheme,
    toggleTheme,
    getTheme,
    getAppliedTheme,
    isDark
  }
}
